package tanks;

import input.AbstractInput;
import input.AbstractInput.direction;

import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.PriorityQueue;

import javax.imageio.ImageIO;

import units.GrassUnit;
import map.Map;
import base_object.ABaseObject;
import bullet.Bullet;

public class PlayerTank extends ATank {
	BufferedImage oldImage, newImage;
	BufferedImage[] imageArr = new BufferedImage[4];
	AbstractInput aI;
	direction prevDir = direction.up;
	direction currDir = direction.up;
	direction nextDir = direction.up;
	Map map;
	int step = 3;
	boolean state = true;
	Bullet bullet;

	public PlayerTank(int x, int y, AbstractInput aI, Map map) {
		super(map);
		setSize(48);
		this.map = map;
		super._x = x;
		super._y = y;
		this.aI = aI;
		rect = new Rectangle(_x, _y, _size, _size);
		try {
			FileInputStream image = new FileInputStream(
					"C:\\Users\\monushka\\Desktop\\BattleCity\\tank.png");
			oldImage = ImageIO.read(image);
			image.close();
			imageArr[0] = rotate(oldImage, 90);// right
			imageArr[1] = rotate(oldImage, -90);// left
			imageArr[2] = rotate(oldImage, 180);// down
			imageArr[3] = oldImage;// up
			newImage = oldImage;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void shoot() {
		direction temp = (currDir==direction.stop)?prevDir:currDir;
		bullet = new Bullet(_x, _y, aI, map, temp);
		map.getQueue().add(bullet);
	}

	@Override
	public void move() {
		if(currDir!=direction.stop)
			prevDir = currDir;
		nextDir = aI.getDir();
		if((super._x%12==0)&&(super._y%12==0))
			currDir = nextDir;
		moveNext(currDir);
		
		if(aI.isShoot()) 
			shoot();
		
		if(bullet!=null)
			bullet.move();
	}

	private void moveNext(direction v) {
		rect = new Rectangle(_y + v.y*step, _x + v.x*step, _size, _size);
		
		if (v.ordinal() < imageArr.length)
			newImage = imageArr[v.ordinal()];
		PriorityQueue<ABaseObject> tempQueue = map.getQueue();
		boolean result = false;
		for(Iterator<ABaseObject> i = tempQueue.iterator(); i.hasNext();) {
			ABaseObject temp = i.next();
			if(!this.equals(temp))
				result = intersects(temp.getRectangle());
			if (result)  {
				return;
			}
		}
		tempQueue = null;
		
		super._x += v.x*step;
		super._y += v.y*step;
		
		if((currDir==direction.stop)&&((super._x%12!=0)||(super._y%12!=0))){
			super._x += prevDir.x*step;
			super._y += prevDir.y*step;
		}
			
		if (super._x < 0)
			super._x = 0;
		if (super._y < 0)
			super._y = 0;
		if (super._x > 576)
			super._x = 576;
		if (super._y > 624)
			super._y = 624;
	}

	@Override
	public void draw(Graphics g) {
		g.drawImage(newImage, _x, _y, null);
	}

}
